<template>
  <div class="ems-freight-detail">
    <el-card>
      <template #header>
        <div style="display: flex; align-items: center; justify-content: space-between;">
          <div style="display: flex; align-items: center; gap: 12px;">
            <el-button @click="goBack" type="primary" plain size="small">
              <el-icon><ArrowLeft /></el-icon>
              返回列表
            </el-button>
            <div style="display: flex; align-items: center; gap: 8px;">
              <el-avatar :src="emsInfo.logoUrl" :size="40" shape="square" />
              <h3 style="margin: 0;">日本邮政EMS运费详情</h3>
            </div>
          </div>
          <div>
            <el-button @click="fetchLatestData" type="warning" size="small" :loading="fetchingData">
              <el-icon><Refresh /></el-icon>
              拉取最新数据
            </el-button>
            <el-button @click="exportToExcel" type="success" size="small">
              <el-icon><Download /></el-icon>
              导出Excel
            </el-button>
          </div>
        </div>
      </template>

      <!-- 基本信息 -->
      <div class="info-section">
        <h4>基本信息</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="物流名称">日本邮政EMS</el-descriptions-item>
          <el-descriptions-item label="物流类型">直邮</el-descriptions-item>
          <el-descriptions-item label="物流速度">2~5日</el-descriptions-item>
          <el-descriptions-item label="重量限制">30000g</el-descriptions-item>
          <el-descriptions-item label="计费模式">详表计费</el-descriptions-item>
          <el-descriptions-item label="税号">A123</el-descriptions-item>
          <el-descriptions-item label="物流特点">最快速，空运，有等级折扣，航空禁运品不可选</el-descriptions-item>
          <el-descriptions-item label="备注">追跡サービス・保険200万円まで</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 数据状态 -->
      <div class="info-section">
        <h4>数据状态</h4>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card shadow="hover" class="status-card">
              <div class="status-item">
                <span class="status-label">数据记录数:</span>
                <span class="status-value">{{ freightData.length }} 条</span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover" class="status-card">
              <div class="status-item">
                <span class="status-label">覆盖区域:</span>
                <span class="status-value">{{ zones.length }} 个</span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover" class="status-card">
              <div class="status-item">
                <span class="status-label">最后更新:</span>
                <span class="status-value">{{ lastUpdateTime }}</span>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 区域说明 -->
      <div class="info-section">
        <h4>区域划分说明</h4>
        <el-row :gutter="20">
          <el-col :span="4" v-for="zone in zones" :key="zone.name">
            <el-card shadow="hover" class="zone-card" :style="{ borderLeft: `4px solid ${zone.color}` }">
              <template #header>
                <div class="zone-header">
                  <span class="zone-number" :style="{ color: zone.color }">{{ zone.name }}</span>
                </div>
              </template>
              <div class="zone-content">
                <p class="zone-description">{{ zone.description }}</p>
                <p class="zone-example">{{ zone.example }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 运费表格 -->
      <div class="info-section">
        <h4>详细运费表</h4>
        
        <!-- 筛选器 -->
        <div class="filter-section">
          <el-row :gutter="20" style="margin-bottom: 16px;">
            <el-col :span="6">
              <el-select v-model="selectedZone" placeholder="选择区域" style="width: 100%">
                <el-option label="全部区域" value="" />
                <el-option 
                  v-for="zone in zones" 
                  :key="zone.name" 
                  :label="zone.name + ' - ' + zone.description" 
                  :value="zone.name" 
                />
              </el-select>
            </el-col>
            <el-col :span="6">
                          <el-select v-model="weightRange" placeholder="重量范围" style="width: 100%">
              <el-option label="全部重量" value="" />
              <el-option label="轻量级 (≤1000g)" value="light" />
              <el-option label="中量级 (1000-5000g)" value="medium" />
              <el-option label="重量级 (5000-15000g)" value="heavy" />
              <el-option label="超重量级 (15000-30000g)" value="super" />
            </el-select>
            </el-col>
            <el-col :span="6">
              <el-input 
                v-model="searchWeight" 
                placeholder="搜索重量(g)" 
                style="width: 100%"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="6">
              <el-button @click="resetFilters" type="info" plain>重置筛选</el-button>
            </el-col>
          </el-row>
        </div>

        <!-- 运费表格 -->
        <el-table :data="filteredFreightData" style="width: 100%" border stripe>
          <el-table-column prop="weight_text" label="重量" width="150" fixed="left">
            <template #default="scope">
              <div class="weight-cell">
                <span class="weight-text">{{ scope.row.weight_text }}</span>
                <span class="weight-value">({{ (scope.row.weight * 1000).toFixed(0) }}g)</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column 
            v-for="zone in zones" 
            :key="zone.name"
            :label="zone.name"
            :prop="zone.name"
            width="180"
          >
            <template #header>
              <div class="zone-table-header">
                <div class="zone-name">{{ zone.name }}</div>
                <div class="zone-desc">{{ zone.description }}</div>
              </div>
            </template>
            <template #default="scope">
              <div class="price-cell">
                <span class="price-value">{{ formatPrice(scope.row.prices[zone.name]) }}</span>
                <span class="price-unit">日元</span>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <!-- <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="filteredFreightData.length"
          :page-sizes="[20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 16px; text-align: right;"
        /> -->
      </div>

      <!-- 价格分析 -->
      <!-- <div class="info-section">
        <h4>价格分析</h4>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card shadow="hover">
              <template #header>
                <span>各区域价格区间</span>
              </template>
              <div class="price-analysis">
                <div v-for="zone in zones" :key="zone.name" class="price-range-item">
                  <span class="zone-label" :style="{ color: zone.color }">{{ zone.name }}:</span>
                  <span class="price-range">
                    最低 {{ getZoneMinPrice(zone.name).toLocaleString() }} 日元,
                    最高 {{ getZoneMaxPrice(zone.name).toLocaleString() }} 日元
                  </span>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover">
              <template #header>
                <span>重量与价格关系</span>
              </template>
              <div class="weight-price-relation">
                            <p>• 轻量级 (≤1000g): 价格相对较低，适合小件物品</p>
            <p>• 中量级 (1000-5000g): 价格适中，适合一般商品</p>
            <p>• 重量级 (5000-15000g): 价格较高，适合重物</p>
            <p>• 超重量级 (15000-30000g): 价格最高，适合大件物品</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div> -->

      <!-- 使用建议 -->
      <!-- <div class="info-section">
        <h4>使用建议</h4>
        <el-alert
          title="区域选择建议"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <ul class="suggestion-list">
              <li><strong>第1区 (中国/韩国/台湾):</strong> 价格最优惠，适合频繁寄送</li>
              <li><strong>第2区 (亚洲其他):</strong> 价格适中，适合一般业务</li>
              <li><strong>第3区 (欧洲/大洋洲):</strong> 价格较高，适合重要文件或高价值物品</li>
              <li><strong>第4区 (美国):</strong> 价格最高，建议选择其他快递方式或批量寄送</li>
              <li><strong>第5区 (中南美/非洲):</strong> 价格较高，适合重要物品或紧急需求</li>
            </ul>
          </template>
        </el-alert>
      </div> -->
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Download, Search, Refresh } from '@element-plus/icons-vue'
import { 
  getEMSFreightData, 
  getZones, 
  getZonePriceStats, 
  searchFreightData,
  type EMSFreightData,
  type ZoneInfo
} from '@/services/emsFreightService'
import { 
  fetchLatestEMSData, 
  validateEMSData, 
  compareData, 
  saveDataToStorage,
  loadDataFromStorage,
  type FetchResult
} from '@/services/emsDataFetcher'

const router = useRouter()

// EMS基本信息
const emsInfo = ref({
  logoUrl: 'https://via.placeholder.com/100x100/00A651/FFFFFF?text=EMS',
  name: '日本邮政EMS',
  type: '国际特快专递',
  speed: '2~5日',
  weightLimit: '30000g',
  calcMode: '详表计费',
  taxCode: 'A123'
})

// 区域信息
const zones = ref<ZoneInfo[]>([])

// 运费数据
const freightData = ref<EMSFreightData[]>([])

// 筛选条件
const selectedZone = ref('')
const weightRange = ref('')
const searchWeight = ref('')

// 分页
const pagination = ref({
  current: 1,
  size: 20
})

// 数据状态
const lastUpdateTime = ref('未更新')

// 筛选后的数据
const filteredFreightData = computed(() => {
  return searchFreightData(freightData.value, selectedZone.value, weightRange.value, searchWeight.value)
})

// 格式化价格
const formatPrice = (price: number) => {
  if (price === undefined || price === null) return '-'
  return price.toLocaleString()
}

// 获取区域最低价格
const getZoneMinPrice = (zoneName: string) => {
  const stats = getZonePriceStats(zoneName)
  return stats ? stats.min : 0
}

// 获取区域最高价格
const getZoneMaxPrice = (zoneName: string) => {
  const stats = getZonePriceStats(zoneName)
  return stats ? stats.max : 0
}

// 重置筛选
const resetFilters = () => {
  selectedZone.value = ''
  weightRange.value = ''
  searchWeight.value = ''
  pagination.value.current = 1
}

// 返回列表
const goBack = () => {
  router.push('/settings/freight-rule')
}

// 导出Excel
const exportToExcel = () => {
  // 这里可以调用之前的Excel导出功能
  ElMessage.success('导出功能开发中...')
}

// 拉取最新数据
const fetchingData = ref(false)
const fetchLatestData = async () => {
  fetchingData.value = true
  try {
    // 保存当前数据用于对比
    const currentData = {
      zones: zones.value,
      freightData: freightData.value
    }
    
    // 从服务拉取最新数据
    const result: FetchResult = await fetchLatestEMSData()
    
    if (result.success && result.data) {
      // 验证数据完整性
      if (validateEMSData(result.data)) {
        // 对比数据变化
        const comparison = compareData(currentData, result.data)
        
        if (comparison.hasChanges) {
          // 更新数据
          zones.value = result.data.zones
          freightData.value = result.data.freightData
          
          // 保存到本地存储
          saveDataToStorage(result.data)
          
          // 显示变化详情
          let message = `成功拉取最新数据！`
          if (comparison.newItems > 0) {
            message += ` 新增 ${comparison.newItems} 项`
          }
          if (comparison.updatedItems > 0) {
            message += ` 更新 ${comparison.updatedItems} 项`
          }
          
          ElMessage.success(message)
          
          // 如果有重要变化，显示详细变化信息
          if (comparison.changes.length > 0) {
            console.log('数据变化详情:', comparison.changes)
          }
        } else {
          ElMessage.info('数据已是最新版本，无需更新')
        }
      } else {
        ElMessage.error('获取的数据格式不正确，请检查数据源')
      }
    } else {
      ElMessage.error(result.message || '拉取数据失败')
    }
  } catch (error) {
    console.error('拉取运费数据失败:', error)
    ElMessage.error('拉取运费数据失败，请稍后重试')
  } finally {
    fetchingData.value = false
  }
}

// 加载运费数据
const loadFreightData = () => {
  try {
    // 首先尝试从本地存储加载数据
    const storedData = loadDataFromStorage()
    
    if (storedData && validateEMSData(storedData)) {
      // 使用本地存储的数据
      freightData.value = storedData.freightData
      zones.value = storedData.zones
      lastUpdateTime.value = storedData.lastUpdated ? new Date(storedData.lastUpdated).toLocaleString('zh-CN') : '本地数据'
      console.log('从本地存储加载EMS运费数据成功:', freightData.value.length, '条记录')
    } else {
      // 从服务加载默认数据
      freightData.value = getEMSFreightData()
      zones.value = getZones()
      lastUpdateTime.value = '默认数据'
      console.log('从服务加载默认EMS运费数据成功:', freightData.value.length, '条记录')
    }
  } catch (error) {
    console.error('加载运费数据失败:', error)
    ElMessage.error('加载运费数据失败')
  }
}

onMounted(() => {
  loadFreightData()
})
</script>

<style scoped>
.ems-freight-detail {
  padding: 16px;
}

.info-section {
  margin-bottom: 24px;
}

.info-section h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-left: 4px solid #409eff;
  padding-left: 12px;
}

/* 区域卡片样式 */
.zone-card {
  height: 100%;
  transition: all 0.3s ease;
}

.zone-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.zone-header {
  text-align: center;
}

.zone-number {
  font-size: 18px;
  font-weight: bold;
}

.zone-content {
  text-align: center;
}

.zone-description {
  margin: 8px 0;
  font-size: 14px;
  color: #606266;
}

.zone-example {
  margin: 0;
  font-size: 12px;
  color: #909399;
  font-style: italic;
}

/* 筛选器样式 */
.filter-section {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

/* 表格样式 */
.weight-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.weight-text {
  font-weight: 500;
  color: #303133;
}

.weight-value {
  font-size: 12px;
  color: #909399;
}

.zone-table-header {
  text-align: center;
}

.zone-name {
  font-weight: 500;
  color: #303133;
}

.zone-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.2;
}

.price-cell {
  text-align: center;
}

.price-value {
  font-weight: 500;
  color: #409eff;
  font-size: 14px;
}

.price-unit {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}

/* 价格分析样式 */
.price-analysis {
  padding: 8px 0;
}

.price-range-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.price-range-item:last-child {
  border-bottom: none;
}

.zone-label {
  font-weight: 500;
}

.price-range {
  color: #606266;
  font-size: 14px;
}

.weight-price-relation {
  padding: 8px 0;
}

.weight-price-relation p {
  margin: 8px 0;
  color: #606266;
  line-height: 1.5;
}

/* 建议列表样式 */
.suggestion-list {
  margin: 8px 0;
  padding-left: 20px;
}

.suggestion-list li {
  margin: 8px 0;
  line-height: 1.6;
  color: #606266;
}

.suggestion-list strong {
  color: #303133;
}

/* 状态卡片样式 */
.status-card {
  height: 100%;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.status-label {
  color: #606266;
  font-size: 14px;
}

.status-value {
  color: #409eff;
  font-weight: 500;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .zone-card {
    margin-bottom: 16px;
  }
  
  .filter-section .el-col {
    margin-bottom: 12px;
  }
}
</style>
